<?php


namespace App\Http\Controllers\Tourist;


use App\Http\Controllers\BaseController;
use App\Models\Client;
use App\Models\Event;
use App\Models\EventEmployee;
use App\Models\Tourist;
use App\Models\TouristEvent;
use App\Models\TouristSearchHistory;
use App\Models\User;
use Illuminate\Http\Request;

class EventController extends BaseController
{
    /**
     * 获取所有事件 /event-list
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getTouristEventList(){
        $event_data = Event::select('id', 'name', 'type', 'photo', 'date', 'permission')->get();
        foreach ($event_data as $value){
            $value['type'] = $value['type'] == 0 ? "course" : "training";
        }
        return $this->returnJson(BaseController::OK, 'success', $event_data);
    }

    /**
     * 通过事件Code获取事件概览 /event/preview/{event_code}
     * @param $event_code
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getTouristEvent($event_code){
        //获取事件信息
        $event_data = Event::where('code', strtoupper($event_code))->select('id', 'client_id', 'name', 'type', 'photo', 'date', 'permission')->first();
        if (!$event_data){
            return $this->returnJson(BaseController::NOTFOUND, 'not found');
        }

        $event_data['type'] = $event_data['type'] == 0 ? "course" : "training";

        //查找客户公司名
        $corporate_name = Client::where('id', $event_data['client_id'])->select('corporate_name')->first();
        $event_data['corporate_name'] = $corporate_name['corporate_name'];
        unset($event_data['client_id']);

        //插入历史搜索
        TouristSearchHistory::insert([
            'event_id'  =>  $event_data['id'],
            'create_time'   =>  time()
        ]);

        return $this->returnJson(BaseController::OK, 'success', $event_data);
    }

    /**
     * 获取游客搜索记录 /history-list
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getTouristHistorySearch(){
        //获取事件数据
        $data = TouristSearchHistory::join('events', 'tourist_search_histories.event_id', 'events.id')
            ->select('events.id', 'events.name', 'events.date', 'events.code')
            ->orderBy('create_time', 'desc')
            ->limit(3)
            ->get();

        return $this->returnJson(BaseController::OK, 'success', $data);
    }

    /**
     * 通过事件Code与电话获取事件详情 /event/detail/{event_code}/{client_phone}
     * @param $event_code
     * @param $client_phone
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getTouristEventDetail($event_code, $client_phone){
        //查找事件
        $event_data = Event::where('code', strtoupper($event_code))->select('id', 'client_id', 'name', 'photo', 'address', 'date', 'permission', 'type', 'status')->first();
        if (!$event_data){
            return $this->returnJson(BaseController::NOTFOUND, 'not found');
        }

        //查找客户
        $client_data = Client::where('id', $event_data['client_id'])->select('id', 'corporate_name', 'firstname', 'lastname', 'phone', 'email')->first();
        if ($client_data['phone'] != $client_phone){
            return $this->returnJson(BaseController::REQUIRED_FIELD_EMPTY, 'the phone number does not match the event code');
        }

        unset($event_data['client_id']);

        //查找员工
        $employee_data = User::join('event_employees', 'users.id', '=', 'event_employees.user_id')
            ->join('events', 'event_employees.event_id', '=', 'events.id')
            ->where('events.id', $event_data['id'])
            ->select('users.id', 'users.email', 'users.photo', 'users.scope', 'users.firstname', 'users.lastname', 'event_employees.status')
            ->get();

        //修改事件的值
        $event_data['permission'] = $event_data['permission'] == 0 ? 'public' : 'private';
        $event_data['type'] = $event_data['type'] == 0 ? "course" : "training";
        if ($event_data['status'] == 0){
            $event_data['status'] = 'pending';
        }else if ($event_data['status'] == 1){
            $event_data['status'] = 'accepted';
        }else if ($event_data['status'] == 2){
            $event_data['status'] = 'finished';
        }

        //修改员工的值
        foreach ($employee_data as $value){
            $value['scope'] = $value['scope'] == 0 ? "course" : "training";
            $value['response'] = $value['status'] == 0 ? 'pending' : 'accepted';
            unset($value['status']);
        }

        $event_data['employees'] = $employee_data;
        $event_data['client'] = $client_data;

        return $this->returnJson(BaseController::OK, 'success', $event_data);
    }

    /**
     * 检查事件 /event/check/{event_id}/{event_code}
     * @param $event_id
     * @param $event_code
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function touristCheckCode($event_id, $event_code){
        $event_data = Event::where('id', $event_id)->select('code')->first();
        //判断事件是否存在
        if (!$event_data){
            return $this->returnJson(BaseController::NOTFOUND, 'not found');
        }

        //判断事件代码是否匹配
        if ($event_data['code'] != $event_code){
            return $this->returnJson(BaseController::UNAUTHORIZED, 'the event code is not correct');
        }

        return $this->returnJson(BaseController::OK, 'success');
    }

    /**
     * 游客注册事件 /enroll/{event_id}
     * @param Request $request
     * @param $event_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function touristRegister(Request $request, $event_id){
        //判断事件是否存在
        $event_data = Event::where('id', $event_id)->first();
        if (!$event_data){
            return $this->returnJson(BaseController::NOTFOUND, 'not found');
        }

        $params = $request->only('email', 'phone', 'firstname', 'lastname');

        //判断为空
        if (empty($params['email']) || empty($params['phone']) || empty($params['firstname']) || empty($params['lastname'])){
            return $this->returnJson(BaseController::REQUIRED_FIELD_EMPTY, 'data cannot be processed');
        }

        //判断邮箱是否已经注册
        $is_email_exists = Tourist::join('tourist_events', 'tourists.id', 'tourist_events.tourist_id')
            ->where([
                'tourists.email'            => $params['email'],
                'tourist_events.event_id'   => $event_id
            ])->first();

        if ($is_email_exists){
            return $this->returnJson(BaseController::REQUIRED_FIELD_EMPTY, 'This email address has already been taken');
        }

        //注册游客
        $tourist_data = Tourist::where([
            'email'     =>  $params['email'],
            'phone'     =>  $params['phone']
        ])->select('id')->first();

        //判断当前游客是否已经注册
        if ($tourist_data){
            $id = TouristEvent::insertGetId([
                'tourist_id'=>  $tourist_data['id'],
                'event_id'  =>  $event_id,
                'firstname' =>  $params['firstname'],
                'lastname'  =>  $params['lastname']
            ]);
            return $this->returnJson(BaseController::OK, 'success', $id);
        }

        $tourist_id = Tourist::insertGetId([
            'email'     =>  $params['email'],
            'phone'     =>  $params['phone']
        ]);

        $id = TouristEvent::insertGetId([
            'tourist_id'=>  $tourist_id,
            'event_id'  =>  $event_id,
            'firstname' =>  $params['firstname'],
            'lastname'  =>  $params['lastname']
        ]);
        return $this->returnJson(BaseController::OK, 'success', $id);
    }

    /**
     * 通过email和电话号码(phone)查找注册 /enroll/{email}/{phone}
     * @param $email
     * @param $phone
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getTouristEventRegister($email, $phone){
        //查找游客事件
        $tourist_data = Tourist::join('tourist_events', 'tourists.id', 'tourist_events.tourist_id')
            ->where([
                'tourists.email'    =>  $email,
                'tourists.phone'    =>  $phone
            ])->select('tourist_events.id', 'tourist_events.event_id', 'tourist_events.firstname', 'tourist_events.lastname')
            ->get()
            ->toArray();

        if (!$tourist_data){
            return $this->returnJson(BaseController::NOTFOUND, 'not found');
        }

        //获取游客事件的信息
        foreach ($tourist_data as $key => $value){
            $event_data = Event::where('id', $value['event_id'])->select('name', 'photo', 'date')->first();
            unset($tourist_data[$key]['event_id']);
            $tourist_data[$key]['event'] = $event_data;
        }

        return $this->returnJson(BaseController::OK, 'success', $tourist_data);
    }
}
